package cn.itcast.bos.web.action.bc;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.domain.bc.Region;
import cn.itcast.bos.utils.PinYin4jUtils;
import cn.itcast.bos.web.action.base.BaseAction;

@Controller("regionAction")
@Scope("prototype")
@Namespace("/bc")
@ParentPackage("bos")
public class RegionAction extends BaseAction<Region> {

	// 1: struts2 接受上传文件 由 默认栈 拦截器 FileUploadInterceptor
	private File upload;

	public void setUpload(File upload) {
		this.upload = upload;
	}

	@Action(value = "regionAction_ajaxListDistrict")
	public String ajaxListDistrict() {
		try {
			// 查所有区域信息
			List<String> regions = regionService.findAllDistrict(model.getCity());
			getValueStack().push(regions);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		return SUCCESS;
	}

	@Action(value = "regionAction_ajaxListCity")
	public String ajaxListCity() {
		try {
			// 查所有区域信息
			List<String> regions = regionService.findAllCity(model.getProvince());
			getValueStack().push(regions);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		return SUCCESS;
	}

	@Action(value = "regionAction_ajaxListProvince")
	public String ajaxListProvince() {
		try {
			// 查所有区域信息
			List<String> regions = regionService.findAllProvince();
			getValueStack().push(regions);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		return SUCCESS;
	}

	@Action(value = "regionAction_ajaxList")
	public String ajaxList() {
		try {
			// 查所有区域信息
			String paramValue = (String) getParameter("q");
			List<Region> regions = regionService.findAll(paramValue);
			getValueStack().push(regions);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		return SUCCESS;
	}

	@Action(value = "regionAction_validRegionIdUnique")
	public String validRegionIdUnique() {
		Map<String, Object> results = new HashMap<String, Object>();
		try {
			Region r = regionService.findRegionById(model.getId());// ajax 发送id 获取 调用业务层查区域对象是否存在
			if (r != null) {
				// 数据库存在添加区域id 记录 客户端不可以添加
				results.put("flag", false);// 返回false
			} else {
				// 数据库没有id 对应数据记录 可以添加 返回true
				results.put("flag", true);
			}
		} catch (Exception e) {
			results.put("flag", false);// 异常 不可以添加!
		}
		getValueStack().push(results);
		return SUCCESS;
	}

	/**
	 * action 利用poi 将excel 文件数据解析 封装到 List<Region> 集合
	 * 
	 * @return
	 * @throws Exception
	 * @throws FileNotFoundException
	 */
	@Action(value = "regionAction_importData")
	public String importData() throws Exception {
		Map<String, Object> results = new HashMap<String, Object>();
		try {
			// poi 解析文件 学习 poi 解析 excel 类库 数据 插入到数据库 region 数据 List<Region>
			// 1: 获取excel文件对象 HSSFWorkBook 对象
			HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(upload));
			// 2: 获取excel数据 获取 sheet --->row---->cell--->value---->Region.setXXX()--->list.add(region)
			HSSFSheet sheet = workbook.getSheetAt(0);
			List<Region> regions = new ArrayList<Region>();
			for (Row row : sheet) {
				// row 当前sheet 每一个行对象
				// 第一行不要解析 排除
				if (row.getRowNum() == 0) {
					continue;
				}
				// 读取每一行数据
				Region r = new Region();
				r.setId(row.getCell(0).getStringCellValue());// 区域编号 添加数据库表region中 注解采用assigned
				r.setProvince(row.getCell(1).getStringCellValue());
				r.setCity(row.getCell(2).getStringCellValue());
				r.setDistrict(row.getCell(3).getStringCellValue());
				r.setPostcode(row.getCell(4).getStringCellValue());
				// pingyin4j 实现 省市区 简记码生成
				String provice = row.getCell(1).getStringCellValue();// 省
				String city = row.getCell(2).getStringCellValue();// 北京市
				String district = row.getCell(3).getStringCellValue();// 区域
				provice = provice.substring(0, provice.length() - 1);// 北京
				city = city.substring(0, city.length() - 1);// 北京
				district = district.substring(0, district.length() - 1);// 东城
				String[] shortArr = PinYin4jUtils.getHeadByString(provice + city + district);
				String shortcode = getStringFromArray(shortArr);// 抽取方法
				r.setShortcode(shortcode);// 简码 默认
				String[] cityArr = PinYin4jUtils.getHeadByString(city);
				String cityCode = getStringFromArray(cityArr);// 抽取方法
				r.setCitycode(cityCode);// 市去掉即可
				// getStringCellValue() 只能获取 字符类型数据
				regions.add(r);
			}
			// 3: 调用业务层
			regionService.importData(regions);
			results.put("flag", true);
		} catch (Exception e) {
			e.printStackTrace();
			results.put("flag", false);
		}
		getValueStack().push(results);
		return SUCCESS;
	}

	private String getStringFromArray(String[] cityArr) {
		if (cityArr != null && cityArr.length != 0) {
			StringBuffer sb = new StringBuffer();
			for (String s : cityArr) {
				sb.append(s);
			}
			return sb.toString();
		}
		return null;
	}

}
